﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//using SkypeDialer.crm;
using SkypeDialer.Classes;
using System.ComponentModel;


namespace SkypeDialer
{
    public partial class Dialer : System.Web.UI.Page
    {
        string onLoadScript = "<script>function OnClLoad() {\n";


        public Dialer()
        {
        }

        public override void Dispose()
        {
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string orgName = Request.QueryString["orgname"];
            if (orgName==string.Empty || orgName==null)
            {
                AddErrorMessage(new ArgumentException("Не указано имя организации"));
                return;
            }

            // Получаем параметры
            string typename = Request.QueryString["typename"];
            if (typename==string.Empty || typename==null)
            {
                AddErrorMessage(new ArgumentException("Не указано имя сущности"));
                return;
            }

            string id = Request.QueryString["id"];
            if (id==string.Empty || id==null)
            {
                AddErrorMessage(new ArgumentException("Не указан идентификатор объекта"));
                return;
            }

            FillPage(orgName, typename, id);
        }

        private void FillPage(string orgName, string typename, string id)
        {
            // Now only CRM-adapter exists
            IDataAdapter dataAdapter = new CrmDataAdapter(orgName, Request.Url);

            List<ContactInfo> contactInfos = new List<ContactInfo>();
            try
            {
                // Getting contact info
                contactInfos = dataAdapter.GetContacts(id, typename);
            }
            catch (Exception ex)
            {
                AddErrorMessage(ex);
            }

            // Adding controls to the page
            foreach (ContactInfo ci in contactInfos)
            {
                AddPhone(ci);
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Onload", onLoadScript + "\n}</script>");
        }

        private void AddErrorMessage(Exception ex)
        {
            Errors.InnerHtml = Errors.InnerHtml+"<span class='ErrorMessage'>" + ex.Message + @"</span>";
        }


        private void AddPhone(ContactInfo ci)
        {
            System.Web.UI.HtmlControls.HtmlTableRow row = new System.Web.UI.HtmlControls.HtmlTableRow();

            System.Web.UI.HtmlControls.HtmlTableCell cell;
            
            //Phone name cell
            cell = new System.Web.UI.HtmlControls.HtmlTableCell();
            cell.InnerHtml = "&nbsp;&nbsp;&nbsp;" + ci.CallingIdName;
            row.Cells.Add(cell);

            // Status Cell
            cell = new System.Web.UI.HtmlControls.HtmlTableCell();
            if (ci.IsStatusAvailable)
            {
                cell.InnerHtml = "&nbsp;&nbsp;&nbsp;<img id='img" + ci.CallingId.GetHashCode().ToString() + "' />";
                onLoadScript = onLoadScript + "\nGetUserStatus('" + ci.CallingId + "', document.getElementById('img" + ci.CallingId.GetHashCode().ToString() + "'));";
            }   
            row.Cells.Add(cell);

            
            // Ячейка с номером
            cell = new System.Web.UI.HtmlControls.HtmlTableCell();
            cell.InnerText = ci.CallingId;
            row.Cells.Add(cell);

            // Ячейка с кнопкой Позвонить
            if (ci.IsCallAvailable)
            {
                cell = new System.Web.UI.HtmlControls.HtmlTableCell();
                cell.InnerHtml = "<img src='/ISV/sharp-team.com/SkypeAddon/_imgs/phone.png' class='img_button' onclick=\"Dial('" + ci.CallingId + "')\" title='Place a call' />";

                row.Cells.Add(cell);
            }

            // Ячейка с кнопкой Видеозвонка
            if (ci.IsVideoCallAvailable)
            {
                cell = new System.Web.UI.HtmlControls.HtmlTableCell();
                cell.InnerHtml = "<img src='/ISV/sharp-team.com/SkypeAddon/_imgs/video.png' class='img_button' onclick=\"VideoDial('" + ci.CallingId + "')\" title='Place a videocall' />";

                row.Cells.Add(cell);
            }

            // Ячейка с кнопкой Чата
            if (ci.IsChatAvailable)
            {
                cell = new System.Web.UI.HtmlControls.HtmlTableCell();
                cell.InnerHtml = "<img src='/ISV/sharp-team.com/SkypeAddon/_imgs/chat.png' class='img_button' onclick=\"Chat('" + ci.CallingId + "')\" title='Start a chat' />";

                row.Cells.Add(cell);
            }

            // TODO Ячейка с кнопкой SMS
            //if (ci.IsSMSAvailable)
            //{
            //    cell = new System.Web.UI.HtmlControls.HtmlTableCell();
            //    cell.InnerHtml = "<img src='/_imgs/sms.png' onclick=\"Chat('" + ci.CallingId + "')\" title='Send SMS' />";

            //    row.Cells.Add(cell);
            //}

            fields.Rows.Add(row);
        }

        #region Obsolete
        /*private string ClearPhoneNumber(string phonenumber)
        {
            string clean = string.Empty;

            char[] symbols = new char[] {'+', '0','1','2','3','4','5','6','7','8','9'};

            foreach(char ch in phonenumber.ToCharArray())
            {
                clean += symbols.Contains(ch) ? ch.ToString() : string.Empty;
            }

            return clean;
        }*/
        #endregion

    }
}